﻿namespace UnitFundProfitability
{
	using System;
	using System.Collections.Generic;
	using System.Windows;
	using System.Windows.Documents;
	using UnitFundProfitability.BusinessLogic;

	/// <summary>
	/// Interaction logic for Movements.xaml.
	/// </summary>
	public partial class Movements : Window
	{
		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="Movements"/> class.
		/// </summary>
		public Movements()
		{
			InitializeComponent();
			IList<UnitFund> unitFunds = Manager.GetUnitFunds();
			SourceUnitFund.DataContext = unitFunds;
			DestinationUnitFund.DataContext = unitFunds;
			MovementDate.SelectedDate = DateTime.Today.AddDays(-1);
			AddMovement.Click += new RoutedEventHandler(AddMovement_Click);
		}
		#endregion

		#region Methods
		/// <summary>
		/// Handles the Click event of the AddMovement control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
		public void AddMovement_Click(object sender, RoutedEventArgs e)
		{
			UnitFund sourceUnitFund = SourceUnitFund.SelectedValue as UnitFund;
			UnitFund destinationUnitFund = DestinationUnitFund.SelectedValue as UnitFund;
			if (sourceUnitFund == null)
			{
				MessageBox.Show("Please, select source unit fund.", "Select unit fund");
			}
			else if (destinationUnitFund == null)
			{
				MessageBox.Show("Please, select destination unit fund.", "Select unit fund");
			}
			else if (sourceUnitFund.FundId == destinationUnitFund.FundId)
			{
				MessageBox.Show("Source unit fund should not be the same as destination unit fund.", "Select unit fund");
			}
			else if (!MovementDate.SelectedDate.HasValue)
			{
				MessageBox.Show("Please, select date.", "Select date");
			}
			else
			{
				decimal unitsAmount = 0;
				if ((!string.IsNullOrWhiteSpace(UnitsAmount.Text) && !decimal.TryParse(UnitsAmount.Text, out unitsAmount)) || unitsAmount < 0)
				{
					MessageBox.Show("Please, enter a valid unis amount.", "Invalid number");
				}
				else
				{
					Manager.AddMovement(unitsAmount, sourceUnitFund, destinationUnitFund, MovementDate.SelectedDate.Value);
				}
			}
		}
		#endregion
	}
}